package cn.anosi.controller.auth;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.anosi.controller.BaseController;
import cn.anosi.entity.auth.Role;
import cn.anosi.page.PageData;

@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {
	/**
	 * 角色列表页面
	 * @return
	 */
	@RequestMapping(value = "/list", method=RequestMethod.GET)
	public String list(){
		return "auth/role_list";
	}
	
	/**
	 * 角色列表数据表格
	 * @return
	 */
	@RequestMapping(value = "/list", method=RequestMethod.POST)
	@ResponseBody
	public PageData<Role> roles(){
		PageData<Role> pageData = new PageData<Role>();
		pageData.setData(roleService.findAll());
		return pageData;
	}
	
	/**
	 * 添加角色页面
	 * @return
	 */
	@RequestMapping(value = "/add", method=RequestMethod.GET)
	public String add(){
		return "auth/role_add";
	}
	
	/**
	 * 添加角色
	 * @param roles
	 * @return
	 */
	@RequestMapping(value = "/add", method=RequestMethod.POST)
	@ResponseBody
	public Role add(@RequestBody List<Role> roles){
		Role role = roles.get(0);
		role.setCreateTime(new Date());
		role.setIsDel("0");
		return roleService.save(role);
	}
	
	@RequestMapping(value = "/edit", method=RequestMethod.GET)
	public String edit(Integer id, Model model){
		model.addAttribute("role", roleService.getById(id));
		return "auth/role_add";
	}
	
	@RequestMapping(value = "/delete", method=RequestMethod.POST)
	@ResponseBody
	public int delete(Integer id){
		return roleService.delete(id);
	}
	
	@RequestMapping(value = "/batchDel", method=RequestMethod.POST)
	@ResponseBody
	public int batchDel(@RequestBody List<Serializable> ids){
		return roleService.batcahDel(ids);
	}
	
	/**
	 * 角色树
	 * @return
	 */
	@RequestMapping(value="/tree", method=RequestMethod.POST)
	@ResponseBody
	public List<Role> tree(){
		return roleService.findAll();
	}
	
	/**
	 * 获取角色关联的所有权限id
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/permissionIds", method = RequestMethod.POST)
	@ResponseBody
	public List<Integer> permissionIds(Integer id){
		return rolePermissionService.getPermissionIds(id);
	}
	
	/**
	 * 分配权限
	 * @param ids
	 * @return
	 */
	@RequestMapping(value="/associatePermission", method = RequestMethod.POST)
	@ResponseBody
	public int associatePermission(@RequestBody List<Integer> ids){
		if(null != ids && ids.size() > 0){
			Integer roleId = ids.get(0);
			ids.remove(0);
			return rolePermissionService.associatePermission(roleId, ids);
		}
		return 0;
	}
}
